package com.action.table;

import com.action.table.TableResultView;

import javax.swing.*;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.util.Enumeration;

public class JTableView {
    TableResultView trv=null;
    JTable jt=null;
    JScrollPane jsp=null;
    private int sumAll;
    /**
     * 构造函数
     * @param Result 二维的字符串结果
     */
    public JTableView(String[][] Result){
        trv=new TableResultView(Result);
        jt=new JTable(trv);
        jt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        FitTableColumns(jt);
    }

    /**
     * 获取JTable表格
     * @return 返回JTable类型
     */
    public JTable getJTable(){
        return this.jt;
    }

    public JScrollPane getJScrollPane(){
        jsp=new JScrollPane(this.jt);
        return this.jsp;
    }

    /**
     * 实现JTable的自适应列宽
     * @param myTable JTable的实例
     */
    private void FitTableColumns(JTable myTable){
        JTableHeader header = myTable.getTableHeader();
        int rowCount = myTable.getRowCount();
        Enumeration<TableColumn> columns = myTable.getColumnModel().getColumns();
        while(columns.hasMoreElements()){
            TableColumn column = (TableColumn)columns.nextElement();
            int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
            int width = (int)myTable.getTableHeader().getDefaultRenderer()
                    .getTableCellRendererComponent(myTable, column.getIdentifier()
                            , false, false, -1, col).getPreferredSize().getWidth();
            for(int row = 0; row<rowCount; row++){
                int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable,
                        myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();
                width = Math.max(width, preferedWidth);
            }
            header.setResizingColumn(column); // 此行很重要
            column.setWidth(width+myTable.getIntercellSpacing().width+10);
            sumAll+=width+myTable.getIntercellSpacing().width+10;
        }
    }
    public int getSumAll(){
        //加上滚动条的宽度
        return this.sumAll+36;
    }
}
